<?php // vim:fenc=utf-8:filetype=php:ts=4

require('config.php');
require('functions.php');
require('definitions.php');
require('../config/net.php');

$logscale   = (boolean)read_var('logarithmic', $_GET, false);
$tinylegend = (boolean)read_var('tinylegend', $_GET, false);

load_graph_definitions($logscale, $tinylegend);

function run_rrd_graph($host, $plugin, $pinsts, $type, $tinsts, $dir) {
    global $config, $MetaGraphDefs;
    if ( preg_match("/@merge/", $tinsts) ) {
        $all_tinst = collectd_list_types($host, $plugin, $pinsts, $type);
        $tmp = $MetaGraphDefs[$type]($host, $plugin, $pinsts, $type, $all_inst, $opts);
    }
    else {
        $tmp = collectd_draw_generic("hour", $host, $plugin, $pinsts, $type, $tinsts);
    }

    //get the hour graph and generate day, week, month and year graph replacing the timespan
    if( !is_dir($config['imgpath'].$plugin.'/'.$dir) ) {
        mkdir($config['imgpath'].$plugin.'/'.$dir, 0755, true);
    }
    foreach ($config['timespan'] as &$ts) {
        $rrd_cmd = str_replace("'-'", ' '.$config['imgpath'].$plugin.'/'.$dir.'/'.$ts['name'].'.png ', $tmp);
        $rrd_cmd = str_replace("'-3600'", ' -'.$ts['seconds'].' ', $rrd_cmd);
        system($rrd_cmd);
    }
}

$plugin=$_GET['plugin'];
$type=$_GET['type'];
$net = new Net();
$out = $net->readDataFromSystem();
$host=$out['hostname'];

switch($plugin) {
    case "interface":
        if(isset($_GET['gettype'])) {
            $dev = array();
            foreach ( $out['interfaces'] as $tmp ) {
                 array_push($dev, $tmp['device']);
            }
            print(json_encode($dev));
        }
        else {
            $tinsts = $type;
            run_rrd_graph($host, $plugin, null, "if_octets", $tinsts, $tinsts);
        }
        break;
    case "cpu":
        if(isset($_GET['gettype'])) {
            $pinsts = collectd_list_plugins($host, $plugin);
            print(json_encode($pinsts));
        }
        else {
            $pinsts = $type;
            run_rrd_graph($host, $plugin, $pinsts, "cpu", "@merge", $pinsts);
        }
        break;
    case "processes":
        if(isset($_GET['gettype'])) {
            print(json_encode(""));
        }
        else {
            $pinsts = $type;
            run_rrd_graph($host, $plugin, null, "ps_state", "@merge", "");
        }
        break;
    case "load":
        if(isset($_GET['gettype'])) {
            print(json_encode(""));
        }
        else {
            run_rrd_graph($host, $plugin, null, "load", null, "");
        }
        break;
    case "memory":
        if(isset($_GET['gettype'])) {
            print(json_encode(""));
        }
        else {
            run_rrd_graph($host, $plugin, null, "memory", "@merge", "");
        }
        break;
}

?>
